const db = require('../modules/db')
const moment = require('moment')

//评论

exports.list = async (req, res, next) => {
  //通过文章ID显示评论
  try {
    const {id} = req.params
    const sqlStr = `SELECT * FROM comments WHERE topic_id = ${id}`
    const ret = await db.query(sqlStr)
    res.status(200).json(ret)
  } catch(e) {
    next(e)
  }

}

exports.create = async (req, res, next) => {
  try {
    const {content = '', topic_id} = req.body
    const sqlStr = `
      INSERT INTO comments (content, create_time, modify_time, topic_id, user_id) 
      VALUE(
        '${content}',
        '${moment().format('YYYY-MM-DD  h:mm:ss ')}',
        '${moment().format('YYYY-MM-DD  h:mm:ss ')}',
        '${topic_id}',
        '${req.session.user.id}'
      )`
      const {insertId}= await db.query(sqlStr)
      const [ret] = await db.query(`SELECT * FROM comments WHERE id = ${insertId}`)
      res.status(200).json(ret)
  } catch(err) {
    next(err)
  }
}

exports.update = (req, res, next) => {

}

exports.delete = async (req, res, next) => {
  try {
    const {id} = req.params
    const sqlStr = `DELETE FROM comments WHERE id = ${id}`
    await db.query(sqlStr)
    res.status(200).json({})
  } catch(e) {
    next(e);
  }
}
